﻿using Core.RVO;
using UnityEngine;

namespace Core
{
    // ReSharper disable once InconsistentNaming
    public class RVOSystem : Core.Entity, IAwake, IUpdate
    {
        public AgentSystem Agents { get; private set; }
        public KdTree KdTree { get; private set; }
        public ObstacleSystem Obstacles { get; private set; }
        public WorkerSystem Workers { get; private set; }

        public void Awake()
        {
            Agents = Add<AgentSystem>();
            Obstacles = Add<ObstacleSystem>();
            KdTree = Add<KdTree>();
            Workers = Add<WorkerSystem>();

            Agents.DefaultNeighborDis = 15.0f;
            Agents.DefaultMaxNeighbors = 10;
            Agents.DefaultTimeHorizon = 5.0f;
            Agents.DefaultTimeHorizonObst = 5.0f;
            Agents.DefaultRadius = 2.0f;
            Agents.DefaultMaxSpeed = 2.0f;
            Agents.DefaultVelocity = Vector2.zero;

            KdTree.BuildObstacleTree();

            Workers.SetNumWorkers(0);
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();
        }

        public int QueryNearAgent(Vector2 point, float radius)
        {
            if (Agents.Count == 0)
                return -1;
            return KdTree.QueryNearAgent(point, radius);
        }

        public void ProcessObstacles()
        {
            KdTree.BuildObstacleTree();
        }

        public void Update()
        {
            Workers.SetAgentCount(Agents.Count);

            KdTree.BuildAgentTree();

            Workers.Update();
        }
    }
}
